﻿//************************************************************************************************************
// CoNatural.Threading.dll
// Author: Roger Torres
//************************************************************************************************************
// You can use, modify, and distribute the source code and executable programs based on the source code.
// This source code is provided "as is" and without warranties as to performance or merchantability. 
// The author and/or distributors of this source code may have made statements about this source code. 
// Any such statements do not constitute warranties and shall not be relied on by the user in deciding 
// whether to use this source code. This source code is provided without any express or implied warranties 
// whatsoever. Because of the diversity of conditions and hardware under which this source code may be used, 
// no warranty of fitness for a particular purpose is offered. The user is advised to test the source code 
// thoroughly before relying on it. The user must assume the entire risk of using the source code.
//************************************************************************************************************

using System;

namespace CoNatural.Threading.Async {
   /// <summary>
   /// Returns Serial of T action results.
   /// </summary>
   /// <typeparam name="T">The result type.</typeparam>
   public class Return<T> : AsyncAction {
      /// <summary>
      /// The returned value to be assigned as the result of a Serial of T action.
      /// </summary>
      public T Value { get; private set; }

      /// <summary>
      /// Constructor. These actions don't have a name or raise events.
      /// </summary>
      /// <param name="value">The returned value.</param>
      public Return(T value)
         : base(string.Empty, false) {
         Value = value;
      }

      /// <summary>
      /// Assigns the returned value as the result of a Serial of T source action.
      /// An exception is thrown if the source action is not a Serial of T.
      /// </summary>
      /// <param name="source">The source async action.</param>
      /// <param name="nextAction">The delegate to continue.</param>
      internal override void BeginInvoke(AsyncAction source, Action nextAction) {
         if (source is Serial<T>) {
            ((Serial<T>)source).Result = Value;
            nextAction();
         }
         else
            throw new InvalidAsyncActionException(source, "Source of Return<T> must be Serial<T>.");
      }
   }
}
